//
//  CameraCollectingAlert.swift
//  ZhiTing
//
//  Created by macbook on 2022/5/9.
//

import UIKit
import SwiftUI
import IQKeyboardManagerSwift

class CameraCollectingAlert: UIView {
    
    var clickCallback: ((_ name: String) -> ())?
    let limitText = 6
    private lazy var cover = UIView().then {
        $0.backgroundColor = .black.withAlphaComponent(0.3)
        $0.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismiss)))
    }
    
    private lazy var container = UIView().then {
        $0.backgroundColor = .custom(.white_ffffff)
        $0.layer.cornerRadius = 10
        $0.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(tapAction)))

    }
    
    private lazy var titleLabel = Label().then {
        $0.font = .font(size: 16, type: .bold)
        $0.textColor = .custom(.black_333333)
        $0.text = "收藏位置".localizedString
    }
    
    private lazy var closeBtn = Button().then {
        $0.setImage(.assets(.close_button), for: .normal)
        $0.isEnhanceClick = true
        $0.clickCallBack = { [weak self] _ in
            self?.dismiss()
        }
    }

    private lazy var line1 = UIView().then {
        $0.backgroundColor = .custom(.gray_eeeeee)
    }
    
    lazy var placeImgView = ImageView().then {
        $0.image = .assets(.camera_placehoder_icon)
        $0.layer.cornerRadius = 4
        $0.clipsToBounds = true
        $0.contentMode = .scaleAspectFill
    }
    
    private lazy var placeTextfield = UITextField().then {
        $0.attributedPlaceholder = NSAttributedString(string: "请输入位置名称（1-6字）".localizedString, attributes: [NSAttributedString.Key.font : UIFont.font(size: 14, type: .bold), NSAttributedString.Key.foregroundColor : UIColor.custom(.gray_94a5be)])
        $0.borderStyle = .none//无边框
        $0.textAlignment = .center
        $0.delegate = self
    }
    
    private lazy var tipsLabel = Label().then {
        $0.text = "* 保存成功后，可将摄影机快速转动到常看位置"
        $0.textColor = .custom(.gray_94a5be)
        $0.font = .font(size: 14, type: .regular)
    }
    
    private lazy var line2 = UIView().then {
        $0.backgroundColor = .custom(.gray_eeeeee)
    }
    private lazy var saveBtn = Button().then {
        $0.setTitle("保存".localizedString, for: .normal)
        $0.setTitleColor(.custom(.white_ffffff), for: .normal)
        $0.backgroundColor = .custom(.blue_2da3f6)
        $0.titleLabel?.font = .font(size: 14, type: .medium)
        $0.layer.cornerRadius = 10
        $0.clipsToBounds = true
        $0.isEnabled = false
        $0.alpha = 0.5
        $0.clickCallBack = { [weak self] _ in
            print("保存成功")
            self?.clickCallback?(self?.placeTextfield.text ?? "")
            self?.dismiss()
        }
    }

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
        setupConstraints()
    }
    
    private func setupViews(){
        addSubview(cover)
        addSubview(container)
        container.addSubview(titleLabel)
        container.addSubview(closeBtn)
        container.addSubview(line1)
        container.addSubview(placeImgView)
        container.addSubview(placeTextfield)
        container.addSubview(line2)
        container.addSubview(tipsLabel)
        container.addSubview(saveBtn)
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow(note:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
        
    }
    
    @objc func keyBoardWillShow(note: NSNotification) {
        //1
        let userInfo  = note.userInfo! as NSDictionary
        //2
        let  keyBoardBounds = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let duration = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //4
        let deltaY = keyBoardBounds.size.height
        //5
        let animations:(() -> Void) = {
            self.container.transform = CGAffineTransform(translationX: 0,y: -deltaY)
        }
        
        container.isHidden = false
        if duration > 0 {
            let options = UIView.AnimationOptions(rawValue: UInt((userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as! NSNumber).intValue << 16))
            UIView.animate(withDuration: duration, delay: 0, options:options, animations: animations, completion: nil)
        } else{
            animations()
        }
    }
    
    @objc private func keyboardHide(_ notification:Notification) {
        UIView.animate(withDuration: 0.3) {
            self.container.transform = .identity
            self.layoutIfNeeded()
        }
        
    }
    
    @objc
    private func tapAction(){
        placeTextfield.resignFirstResponder()
        
    }


    
    private func setupConstraints(){
        cover.snp.makeConstraints {
            $0.edges.equalToSuperview()
        }
        
        container.snp.makeConstraints {
            $0.left.right.equalToSuperview()
            $0.bottom.equalToSuperview().offset(10)
            $0.height.equalTo(400)
        }
        
        titleLabel.snp.makeConstraints {
            $0.top.equalToSuperview().offset(16)
            $0.left.equalToSuperview().offset(16)
        }
        
        closeBtn.snp.makeConstraints {
            $0.centerY.equalTo(titleLabel.snp.centerY)
            $0.right.equalToSuperview().offset(-16)
            $0.height.width.equalTo(12)
        }
        
        line1.snp.makeConstraints {
            $0.left.right.equalToSuperview()
            $0.height.equalTo(0.5)
            $0.top.equalTo(titleLabel.snp.bottom).offset(16)
        }
        
        placeImgView.snp.makeConstraints {
            $0.top.equalTo(line1.snp.bottom).offset(28.5)
            $0.centerX.equalToSuperview()
            $0.width.equalTo(250)
            $0.height.equalTo(150)
        }
        
        placeTextfield.snp.makeConstraints {
            $0.top.equalTo(placeImgView.snp.bottom).offset(20)
            $0.left.right.equalToSuperview()
            $0.height.equalTo(25)
        }
        
        line2.snp.makeConstraints {
            $0.top.equalTo(placeTextfield.snp.bottom)
            $0.left.equalTo(15)
            $0.right.equalTo(-15)
            $0.height.equalTo(0.5)
        }
        
        tipsLabel.snp.makeConstraints {
            $0.top.equalTo(line2.snp.bottom).offset(10)
            $0.left.right.equalTo(line2)
            $0.height.equalTo(15)
        }
        
        saveBtn.snp.makeConstraints {
            $0.bottom.equalTo(-30)
            $0.left.right.equalTo(tipsLabel)
            $0.height.equalTo(50)
        }

    }
    
    convenience init() {
        self.init(frame: CGRect(x: 0, y: 0, width: Screen.screenWidth, height: Screen.screenHeight))
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        container.transform = .init(translationX: 0, y: Screen.screenHeight)
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut) {
            self.container.transform = .identity
            IQKeyboardManager.shared.shouldResignOnTouchOutside = false
        }

    }
    
    override func removeFromSuperview() {
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: {
            self.container.transform = .init(translationX: 0, y: Screen.screenHeight)
        }, completion: { isFinished in
            if isFinished {
                IQKeyboardManager.shared.shouldResignOnTouchOutside = true
                super.removeFromSuperview()
            }
        })
        
    }
    
    @objc
    private func dismiss() {
        removeFromSuperview()
    }


}

extension CameraCollectingAlert: UITextFieldDelegate {
    func textFieldDidChangeSelection(_ textField: UITextField) {
        let text = textField.text ?? ""
        if text.count > limitText {
            textField.text = String(text.prefix(limitText))
        }
        
        
        
        if textField.text?.replacingOccurrences(of: " ", with: "").count == 0 {
            saveBtn.isEnabled = false
            saveBtn.alpha = 0.5
        } else {
            saveBtn.isEnabled = (text.count > 0)
            saveBtn.alpha = 1
        }
    }
}
